﻿using POC.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace wlog.Shell.IO
{
    public class ConfigCommand : Command
    {
        string assignmentStatement;
        string nextCommand;
        public override void Setup(string[] args)
        {
            CommandArgs = args;
            this.CommnadName = args[0].Trim('"');
            TokenizeCommand(args);
            Results.Add("Command Name : " + CommnadName);
            base.CreateTask(() =>
            {
                nextCommand = commandObjectType; //args[1]
                assignmentStatement = objectName; //args[2]
                if (string.IsNullOrEmpty(nextCommand))
                {
                    ShowVariables();
                    // Show help
                }
                else
                {
                    try
                    {
                        ConfigureCommand command = new ConfigureCommand(nextCommand, "", "");
                        if (!string.IsNullOrEmpty(assignmentStatement))
                        {
                            var kp = GetVariable(assignmentStatement); // not working now
                            command = new ConfigureCommand(nextCommand, kp.Key, kp.Value);
                        }                       
                        command.Execute();
                    }
                    catch (Exception commandEx)
                    {
                        Results.Add("Error in executing method : " + nextCommand + " Message : " + commandEx.Message);
                    }
                }
            });
        }
        public void SetupNewConfigReader()
        {

        }
        public KeyValuePair<string, string> GetVariable(string assignString)
        {
            string[] keyvalue = assignString.Trim().Split('=');
            KeyValuePair<string,string> kp = new KeyValuePair<string,string>("","");
            if (keyvalue.Length == 2 && keyvalue[0][0] != '#')
            {
                string key = keyvalue[0].Trim();
                string val = keyvalue[1].Trim();
                kp = new KeyValuePair<string, string>(key, val);
                ApplicationConfiguration.Set(key, val);
                Results.WriteKeyPair(key, val);
            }
            else
            {
                Results.WriteLine("cant parse {0}", assignmentStatement);
            }
            return kp;
        }
        public void ShowVariables()
        {
            var settings = ApplicationConfiguration.List();
            Results.WriteKeyPair("Settings Key", "Settings Value");
            Results.WriteLine("================================================================================");
            foreach (var item in settings)
            {
                Results.WriteKeyPair(item.Key, item.Value);
            }
        }

    }
}
